import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:toys_flutter/api/app.dart';
import 'package:toys_flutter/components/MyImageWidget.dart';
import 'package:toys_flutter/components/RefreshableListView.dart';
import 'package:toys_flutter/components/UserInfo.dart';
import 'package:toys_flutter/utils/style_utils.dart';

// 用户主页
class UserDetail extends StatefulWidget {
  late String userId;

  UserDetail({super.key, required this.userId});

  @override
  State<UserDetail> createState() => _UserDetailState();
}

class _UserDetailState extends State<UserDetail>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  late TabController _tabController;
  Map<String, dynamic>? userData; // 初始化为 null
  List<dynamic>? list; // 初始化为 null

  // 获取用户信息
  void getUserData() async {
    var res = await Api.toysUserInfo({'user_id': widget.userId});
    if (res['code'] == 1) {
      setState(() {
        userData = res['data'];
      });
    }
  }

  // 获取用户动态
  void getUserInfoByType(int type) async {
    var res =
        await Api.toysUserInfoByType({'user_id': widget.userId, 'type': type});
    if (res['code'] == 1) {
      if (type == 2) {
        setState(() {
          list = res['data'].map<Map<String, dynamic>>((item) {
            return {
              ...item,
              'avatar': userData!['avatar'],
              'image': item['image'] is List
                  ? item['image']
                  : item['image'].split(',')
            };
          }).toList();
        });
      } else {
        setState(() {
          list = res['data'];
        });
      }
    }
  }

  void onFollow() async {
    var res = await Api.communityFollow({
      'follow_id': userData!['id'],
      'status': userData!['is_follow'] == 0 ? 1 : 0
    });
    if (res['code'] == 1) {
      if (userData!['is_follow'] == 1) {
        TDToast.showSuccess('已取消关注', context: context);
      } else {
        TDToast.showSuccess('关注成功', context: context);
      }
      getUserData();
    }
  }

  @override
  void initState() {
    super.initState();
    getUserData();
    // 获取图片
    getUserInfoByType(1);
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  // 模拟数据刷新
  Future<void> _refreshData() async {
    try {
      getUserData();
      // 获取图片
      getUserInfoByType(1);
    } catch (e) {
      print('Error: $e');
      TDToast.showIconText('数据刷新失败',
          icon: TDIcons.error,
          direction: IconTextDirection.vertical,
          context: context);
    }
  }

  @override
  Widget build(BuildContext context) {
    if (userData == null) {
      return const Center(
        child: TDLoading(
          size: TDLoadingSize.large,
          icon: TDLoadingIcon.circle,
        ),
      );
    }

    // 计算图片宽度
    final double imageWidth = (MediaQuery.of(context).size.width - 50) / 3;

    return Scaffold(
      appBar: AppBar(
        title: const Text('用户主页'),
      ),
      body: Stack(
        children: [
          RefreshableListView(
            onRefresh: _refreshData,
            children: [
              Padding(
                padding: const EdgeInsets.all(15),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 这里使用 Expanded 包裹 SingleChildScrollView
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 用户信息
                        UserInfo(user: userData),
                        const SizedBox(height: 10),
                        // 动态，关注，粉丝
                        Row(
                          children: [
                            Text('${userData!['community']}动态',
                                style: StyleUtils.mainTextStyle),
                            const SizedBox(width: 10),
                            Text('${userData!['flow']}关注',
                                style: StyleUtils.mainTextStyle),
                            const SizedBox(width: 10),
                            Text('${userData!['p_flow']}粉丝',
                                style: StyleUtils.mainTextStyle),
                          ],
                        ),
                        const SizedBox(height: 20),
                        // 魅力值和财富值
                        Row(
                          children: [
                            TDTag(
                              '${userData!['earnings_all']}魅力值',
                              shape: TDTagShape.round,
                              theme: TDTagTheme.warning,
                              size: TDTagSize.large,
                            ),
                            const SizedBox(width: 10),
                            TDTag(
                              '${userData!['use_money_all']}财富值',
                              shape: TDTagShape.round,
                              theme: TDTagTheme.danger,
                              size: TDTagSize.large,
                            ),
                          ],
                        ),
                        const SizedBox(height: 20),
                        // 标签
                        Wrap(
                          spacing: 10,
                          runSpacing: 10,
                          children: [
                            if (userData != null &&
                                userData!.containsKey('attribute_1') &&
                                userData!['attribute_1'] != null)
                              TDTag(userData!['attribute_1'],
                                  isOutline: true,
                                  isLight: true,
                                  shape: TDTagShape.round,
                                  theme: TDTagTheme.warning),
                            if (userData != null &&
                                userData!.containsKey('attribute_2') &&
                                userData!['attribute_2'] != null)
                              ...userData!['attribute_2']
                                  .split(',')
                                  .map((item) => TDTag(item,
                                      isOutline: true,
                                      isLight: true,
                                      shape: TDTagShape.round,
                                      theme: TDTagTheme.success))
                                  .toList(),
                          ],
                        ),
                        // 个人简介
                        const SizedBox(height: 20),
                        const Text('个人简介', style: StyleUtils.titleTextStyle),
                        const SizedBox(height: 10),
                        Text(userData!['desc'] ?? '这家伙太懒了，什么都没写...',
                            style: StyleUtils.customTextStyle),
                        const SizedBox(height: 10),
                        const TDDivider(),
                        const SizedBox(height: 20),
                      ],
                    ),
                    SizedBox(
                      height: 40,
                      child: TabBar(
                        controller: _tabController,
                        indicatorSize: TabBarIndicatorSize.label,
                        // 标签栏的文字颜色
                        labelColor: Colors.blue,
                        unselectedLabelColor: Colors.black,
                        dividerColor: Colors.transparent,
                        tabs: const [
                          Text('照片'),
                          Text('动态'),
                          Text('视频'),
                        ],
                      ),
                    ),
                    // TabBarView在这里
                    SizedBox(
                      height: (list!.length / 3) * imageWidth + 150,
                      child: TabBarView(
                        controller: _tabController,
                        children: [
                          Wrap(
                            spacing: 10,
                            runSpacing: 10,
                            children: list!.asMap().entries.map((entry) {
                              int index = entry.key;
                              Map<String, dynamic> url = entry.value;
                              return GestureDetector(
                                onTap: () {
                                  final List<String> imageUrls = list!
                                      .map((item) => item['image'] as String)
                                      .toList();
                                  TDImageViewer.showImageViewer(
                                    context: context,
                                    images: imageUrls,
                                    defaultIndex: index, // 传递点击的索引
                                  );
                                },
                                child: MyImageWidget(image: url['image'], imageWidth: imageWidth)
                                // child: TDImage(
                                //   imgUrl: url['image'],
                                //   width: imageWidth,
                                //   height: imageWidth,
                                //   type: TDImageType.roundedSquare,
                                // ),
                              );
                            }).toList(),
                          ),
                          const Center(child: Text('动态')),
                          Wrap(
                            spacing: 10,
                            runSpacing: 10,
                            children: list!.asMap().entries.map((entry) {
                              int index = entry.key;
                              Map<String, dynamic> url = entry.value;
                              return GestureDetector(
                                onTap: () {
                                  final List<String> imageUrls = list!
                                      .map((item) => item['image'] as String)
                                      .toList();
                                  TDImageViewer.showImageViewer(
                                    context: context,
                                    images: imageUrls,
                                    defaultIndex: index, // 传递点击的索引
                                  );
                                },
                                child: MyImageWidget(image: url['image'], imageWidth: imageWidth)
                                // child: TDImage(
                                //   imgUrl: url['image'],
                                //   width: imageWidth,
                                //   height: imageWidth,
                                //   type: TDImageType.roundedSquare,
                                // ),
                              );
                            }).toList(),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),

          // 悬浮按钮
          Positioned(
            bottom: 20,
            left: 0,
            right: 0,
            child: Row(
              children: [
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 10),
                    child: FloatingActionButton(
                      heroTag: 'button1',
                      // 确保这个 tag 是唯一的
                      backgroundColor: Colors.blue,
                      foregroundColor: Colors.white,
                      onPressed: () {
                        // 按钮1的点击事件
                        print('按钮1被点击');
                      },
                      child: const Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [Icon(Icons.chat), Text('打招呼')],
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 10),
                    child: FloatingActionButton(
                      heroTag: 'button2',
                      // 确保这个 tag 是唯一的
                      backgroundColor: userData!['is_follow'] == 1
                          ? Colors.green
                          : Colors.orange,
                      foregroundColor: Colors.white,
                      onPressed: onFollow,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const Icon(Icons.person_add),
                          Text(userData!['is_follow'] == 1 ? '已关注' : '关注')
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
